from nornir import InitNornir
from nornir_utils.plugins.functions import print_result
from nornir_utils.plugins.tasks.files import write_file
from nornir_netmiko import netmiko_send_command
import os


nornir_devs = InitNornir(
    config_file="nornir.yaml"
)


def backup(task):
    cmds = task.host.data['backup_configs']
    max_loops = 180/0.2
    for cmd in cmds:
        show_result = task.run(netmiko_send_command, command_string=cmd,max_loops=max_loops)
        output = show_result.result # Result host result
        cmd_log = cmd.replace(' ','_')+'.log'
        dir = task.host.hostname
        file_name = os.path.join(dir, cmd_log)
        if not os.path.exists(dir):
            os.mkdir(dir)
        write_result = task.run(write_file,
                                filename=file_name,
                                content=output,
                                )
        print(write_result)

# dev = nr.filter(role='spine')
results = nornir_devs.run(task=backup)
print_result(results)
